<?php
/**
 * @package trading
 */
class TradeSetting extends DataObject implements PermissionProvider {
    private static $singular_name = "Trading Setting";
    private static $plural_name = "Trading Settings";
	
	private static $certificate_template = "/trading/images/certificate.png";
    
    private static $db = array(
    	'IsActive' => 'Boolean',
    	'StartDate' => 'Date',
		'Code' => 'Varchar',
    	'Title' => 'Varchar',
    	'TotalUnit' => 'Int',
    	'SellUnit' => 'Int',
    	'BuyUnit' => 'Int',
    	'SellVolume' => 'TradeCurrency',
    	'BuyVolume' => 'TradeCurrency',
    	'Margin' => 'TradeCurrency',
    	'CurrentMargin' => 'TradeCurrency',
    	'MarkupType' => "Enum(array('Amount', 'Percentage'))",
    	'MarkupAmount' => 'TradeCurrency',
    	'MarkupPercentage' => 'Percentage',
        'Price' => 'TradeCurrency',
        'ForceBuyingPrice' => 'Boolean',
        'ForceSellingPrice' => 'Boolean'
    );
	
	private static $has_many = array(
		'TradePrices' => 'TradePrice'
	);
	
	private static $many_many = array(
		'RestrictMembers' => 'Member'
	);
	
	private static $many_many_extraFields = array(
	    'RestrictMembers' => array(
	    	'IncludeTeam' => 'Boolean',
	        'BuyOrder' => 'Boolean',
	        'SellOrder' => 'Boolean',
	        'PurchaseShare' => 'Boolean',
	        'TradeRequest' => 'Boolean'
	    )
	);
	
	private static $default_sort = "Price DESC";

    private static $searchable_fields = array(
    	'IsActive',
    	'StartDate' => array(
			'field' => 'DateField',
			'filter' => 'DateMatchFilter'
		),
		'Code',
		'Title',
        'Margin' => array(
            'filter' => 'GreaterThanOrEqualFilter'
        ),
        'Price' => array(
            'filter' => 'GreaterThanOrEqualFilter'
        )
    );

    private static $summary_fields = array(
    	'IsActive.Nice',
    	'StartDate.Nice',
		'Code',
        'Title',
        'TotalUnit',
        'AvailableUnit',
        'Margin',
        'Markup',
        'Price'
    );
	
	private static $casting = array(
		'Markup' => 'TradeCurrency',
		'IsStarted' => 'Boolean',
		'IsClosed' => 'Boolean',
		'SellFeePercentage' => 'Percentage',
		'BuyFeePercentage' => 'Percentage',
		'AvailableUnit' => 'Int',
		'CurrentUnit' => 'Int',
		'CurrentCompanyUnit' => 'Int',
		'CurrentMemberUnit' => 'Int',
		'CurrentAmount' => 'TradeCurrency'
	);
	
	static function get_available_company_unit_by_price($trade_setting_id, $trade_price){
		$trade_setting = TradeSetting::get()->byID($trade_setting_id);
		if($trade_price > 0 && $trade_setting){
			return $trade_setting->TradePrice($trade_price)->AvailableCompanyUnit;
		}

		return 0;
	}
	
	static function get_available_member_unit_by_price($trade_setting_id, $trade_price){
		$trade_setting = TradeSetting::get()->byID($trade_setting_id);
		if($trade_price > 0 && $trade_setting){
			return $trade_setting->TradePrice($trade_price)->AvailableMemberUnit;
		}

		return 0;
	}

	static function get_available_unit_by_price($trade_setting_id, $trade_price){
		$trade_setting = TradeSetting::get()->byID($trade_setting_id);
		if($trade_price > 0 && $trade_setting){
			return $trade_setting->TradePrice($trade_price)->AvailableUnit;
		}

		return 0;
	}
	
	static function get_limit_member_unit_by_price($trade_setting_id, $trade_price){
		$trade_setting = TradeSetting::get()->byID($trade_setting_id);
		if($trade_price > 0 && $trade_setting){
			return $trade_setting->TradePrice($trade_price)->LimitMemberUnit;
		}

		return 0;
	}
	
	public function fieldLabels($includerelations = true) {
		$labels = parent::fieldLabels($includerelations);
		
		$labels['IsActive'] = _t('TradeSetting.IS_ACTIVE', 'Is Active?');
		$labels['IsActive.Nice'] = _t('TradeSetting.IS_ACTIVE', 'Is Active?');
		$labels['StartDate'] = _t('TradeSetting.START_DATE', 'Start Date');
		$labels['StartDate.Nice'] = _t('TradeSetting.START_DATE', 'Start Date');
		$labels['Code'] = _t('TradeSetting.CODE', 'Code');
		$labels['Title'] = _t('TradeSetting.TITLE', 'Title');
		$labels['TotalUnit'] = _t('TradeSetting.TOTAL_UNIT', 'Total Unit');
		$labels['AvailableUnit'] = _t('TradeSetting.AVAILABLE_UNIT', 'Available Unit');
		$labels['SellUnit'] = _t('TradeSetting.SELL_UNIT', 'Sell Unit');
		$labels['BuyUnit'] = _t('TradeSetting.BUY_UNIT', 'Buy Unit');
		$labels['SellVolume'] = _t('TradeSetting.SELL_VOLUME', 'Sell Volume');
		$labels['BuyVolume'] = _t('TradeSetting.BUY_VOLUME', 'Buy Volume');
		$labels['Margin'] = _t('TradeSetting.MARGIN', 'Margin');
		$labels['CurrentMargin'] = _t('TradeSetting.CURRENT_MARGIN', 'Current Margin');
		$labels['Markup'] = _t('TradeSetting.MARKUP', 'Markup');
		$labels['MarkupType'] = _t('TradeSetting.MARKUP_TYPE', 'Markup Type');
		$labels['MarkupAmount'] = _t('TradeSetting.MARKUP_AMOUNT', 'Markup Amount');
		$labels['MarkupPercentage'] = _t('TradeSetting.MARKUP_PERCENTAGE', 'Markup Percentage');
		$labels['Price'] = _t('TradeSetting.TRADING_PRICE', 'Trading Price');
		$labels['ForceBuyingPrice'] = _t('TradeSetting.FORCE_BUYING_PRICE', 'Force buying price?');
		$labels['ForceSellingPrice'] = _t('TradeSetting.FORCE_SELLING_PRICE', 'Force selling price?');
		$labels['RestrictMembers'] = _t('TradeSetting.RESTRICT_MEMBERS', 'Restrict Members');
		
		return $labels;	
	}

	function getCMSFields() {
		$fields = parent::getCMSFields();
		$fields->makeFieldReadonly('SellUnit');
		$fields->makeFieldReadonly('BuyUnit');
		$fields->makeFieldReadonly('SellVolume');
		$fields->makeFieldReadonly('BuyVolume');
		$fields->makeFieldReadonly('CurrentMargin');
		
		if($this->exists()) {
			$fields->makeFieldReadonly('Code');
            $extra_fields = FieldList::create(
            	ReadonlyField::create('Username', _t('TradeSetting.USERNAME', 'Username')),
            	ReadonlyField::create('Name', _t('TradeSetting.NAME', 'Name')),
				OptionsetField::create('ManyMany[IncludeTeam]', _t('TradeSetting.INCLUDE_TEAM', 'Include Team'), array('1' => _t('TradeSetting.YES', 'Yes'), '0' => _t('TradeSetting.NO', 'No'))),
				OptionsetField::create('ManyMany[BuyOrder]', _t('TradeSetting.BUY_ORDER', 'Buy Order'), array('1' => _t('TradeSetting.YES', 'Yes'), '0' => _t('TradeSetting.NO', 'No'))),
				OptionsetField::create('ManyMany[SellOrder]', _t('TradeSetting.SELL_ORDER', 'Sell Order'), array('1' => _t('TradeSetting.YES', 'Yes'), '0' => _t('TradeSetting.NO', 'No'))),
				OptionsetField::create('ManyMany[PurchaseShare]', _t('TradeSetting.PURCHASE_SHARE', 'Purchase Share'), array('1' => _t('TradeSetting.YES', 'Yes'), '0' => _t('TradeSetting.NO', 'No'))),
				OptionsetField::create('ManyMany[TradeRequest]', _t('TradeSetting.TRADE_REQUEST', 'Trade Request'), array('1' => _t('TradeSetting.YES', 'Yes'), '0' => _t('TradeSetting.NO', 'No')))
			);
            $config = GridFieldConfig_RelationEditor::create();
			$config->removeComponentsByType('GridFieldAddNewButton');
            $config->getComponentByType('GridFieldDetailForm')->setFields($extra_fields);
			$config->getComponentByType('GridFieldAddExistingAutocompleter')->setSearchFields(array('Username', 'Email', 'Surname', 'FirstName'));
			$fields->dataFieldByName('RestrictMembers')->setConfig($config);
        }

		return $fields;
	}

	function TradePrice($trade_price){
		$price = $this->TradePrices()->find('Price', $trade_price);
		if(!$price){
			$price = TradePrice::create()->setField('Price', $trade_price)->setField('TradeSettingID', $this->ID);
			$price->write();
		}
		return $price;
	}
	
	function getIsStarted(){
		return $this->dbObject('StartDate')->InPast();
	}
	
	function getIsClosed(){
		return $this->AvailableUnit <= 0;
	}
	
	function getSellFeePercentage(){
		return 0.1;
	}
	
	function getBuyFeePercentage(){
		return 0;
	}
	
	function getAvailableUnit(){
		return $this->TotalUnit + $this->BuyUnit - $this->SellUnit;
	}
	
	function getCurrentUnit(){
		return TradeSetting::get_available_unit_by_price($this->ID, $this->Price);
	}
	
	function getCurrentAmount(){
		return $this->CurrentUnit * $this->Price;
	}
	
	function getCurrentCompanyUnit(){
		return TradeSetting::get_available_company_unit_by_price($this->ID, $this->Price);
	}
	
	function getCurrentMemberUnit(){
		return TradeSetting::get_available_member_unit_by_price($this->ID, $this->Price);
	}
	
	function getMarkup(){
		if($this->MarkupType == 'Percentage'){
			return $this->Price * $this->MarkupPercentage >= 0.001 ? $this->Price * $this->MarkupPercentage : 0;
		}
		else{
			return $this->MarkupAmount;
		}
	}
	
	function canView($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('VIEW_TradeSetting');
    }

    function canEdit($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('EDIT_TradeSetting');
    }

    function canDelete($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('DELETE_TradeSetting');
    }

    function canCreate($member = false) {
        $extended = $this->extendedCan(__FUNCTION__, $member);
        if($extended !== null) {
            return $extended;
        }
        return Permission::check('CREATE_TradeSetting');
    }

    public function providePermissions() {
        return array(
            'VIEW_TradeSetting' => array(
                'name' => _t('TradeSetting.PERMISSION_VIEW', 'Allow view access right'),
                'category' => _t('TradeSetting.PERMISSIONS_CATEGORY', 'Trade Setting')
            ),
            'EDIT_TradeSetting' => array(
                'name' => _t('TradeSetting.PERMISSION_EDIT', 'Allow edit access right'),
                'category' => _t('TradeSetting.PERMISSIONS_CATEGORY', 'Trade Setting')
            ),
            'DELETE_TradeSetting' => array(
                'name' => _t('TradeSetting.PERMISSION_DELETE', 'Allow delete access right'),
                'category' => _t('TradeSetting.PERMISSIONS_CATEGORY', 'Trade Setting')
            ),
            'CREATE_TradeSetting' => array(
                'name' => _t('TradeSetting.PERMISSION_CREATE', 'Allow create access right'),
                'category' => _t('TradeSetting.PERMISSIONS_CATEGORY', 'Trade Setting')
            )
        );
    }
}
?>